package by.home.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;

public abstract class FrontController extends HttpServlet {

    public ActionManager actionManager;
    static private final Logger log = Logger.getLogger(FrontController.class);

    public FrontController() {
        DOMConfigurator.configure("log4j.xml");
    }

    public void process(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException, ClassNotFoundException {
        initActionManager();
        Action action = actionManager.getActionByPageName(httpServletRequest.getRequestURI());
        Params params = action.executeAndGet(httpServletRequest.getParameterMap());
        httpServletRequest.setAttribute("params", params);
        dispatch(httpServletRequest, httpServletResponse, params.getResponsePage());
    }

    public void dispatch(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String responsePage) throws IOException, ServletException {
        getServletContext().getRequestDispatcher(responsePage).forward(httpServletRequest, httpServletResponse);
    }

    @Override
    public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        try {
            process(httpServletRequest, httpServletResponse);
        } catch (ClassNotFoundException e) {
            log.error(e);
            System.exit(1);
        }
    }

    @Override
    public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        try {
            process(httpServletRequest, httpServletResponse);
        } catch (ClassNotFoundException e) {
            log.error(e);
            System.exit(1);
        }
    }

    public abstract void initActionManager();

}
